const api = require("./api.js");
const storage = require("./storage.js");
/*------微信登录--------*/
exports.login = function() {
  return new Promise((resolve, reject) => {
    wx.login({
      success: function(res) {
        if (res.code) {
          resolve(res.code);
        } else {
          reject(res.errMsg);
        }
      }
    });
  });
};

/*------------------*/
exports.getOpenId = function() {
  var key = "wxopenid";
  return new Promise((resolve, reject) => {
    storage.get(key).then(res => {
      if (res) {
        resolve(res);
      } else {
        this.login().then(code => {
          api.user_xcxJsCode({
            code
          }).then(data => {
            let result = JSON.parse(data.result);
            console.log(result);
            let openid = result.openid;
            // console.log("openid: ", result);
            storage.set(key, result, 60 * 60 * 24);
            storage.set("session_key", result.session_key, 60 * 60 * 24);

            resolve(result);
          });
        });
      };
    });
  });
};